#include "LoginServer.h"
#include "ut_debug.h"
#include "../../include/GTProto.h"
#include "SessionValidator.h"
#include "EndianCast.h"
#include "GateServerRoot.h"
#include "ProxyMgr.h"

CLoginServer * CLoginServer::m_pInstance = NULL;

CLoginServer::CLoginServer( utility::network::pipe * pPipe ):
    IServer(pPipe)
{

}


CLoginServer::~CLoginServer(void)
{
}

void CLoginServer::on_receive( const char * message, uint32 message_length )
{
    uint32 nProtoID = ntohl(*(uint32 *)message);
    if (nProtoID == GT_USER_TOKEN_NTF_ID)
    {
        GT_USER_TOKEN_NTF_PKG * pkg = (GT_USER_TOKEN_NTF_PKG *)(message + sizeof(nProtoID));
        CSessionValidator::Instance()->AddToken(
            ntohl(pkg->nUserID), 
            ntohl(pkg->nToken)
            );
    }
}

void CLoginServer::on_established()
{
    LOG(INFO) << "Connected with login server : "<< utility::network::idtoa(m_pPipe->get_remote_id());

    GT_USER_COUNT_NTF_PKG pkg;
    pkg.count = htons(CProxyMgr::Instance()->GetProxyCount());
    pkg.port = htons(GateServerRoot::Instance()->GetListenerPort());
    Send(GT_USER_COUNT_NTF_ID, &pkg, sizeof(pkg));
}

void CLoginServer::on_disconnected()
{
    //LOG(INFO) << "Disconnected from logie server : "<< utility::network::idtoa(m_pPipe->get_remote_id());
}

void CLoginServer::on_error( int32 error_code, const char * error_message )
{
    //LOG(CRITICAL) << 
    on_disconnected();
}

CLoginServer * CLoginServer::CreateInstance( utility::network::pipe * pPipe )
{
    if (m_pInstance == NULL)
        m_pInstance = new CLoginServer(pPipe);
    return m_pInstance;
}

CLoginServer * CLoginServer::Instance()
{
    return m_pInstance;
}

void CLoginServer::DestroyInstance()
{
    delete m_pInstance;
    m_pInstance = NULL;
}

void CLoginServer::Release()
{
    DestroyInstance();
}

void CLoginServer::Send( uint32 nMsgId, void * Msg, size_t nMsgLen )
{
    size_t nBufSize = sizeof(uint32) + nMsgLen;
    char * buf = (char *)alloca(nBufSize);
    *(uint32 *)buf = htonl(nMsgId);
    memcpy(buf + sizeof(uint32), Msg, nMsgLen);
    send(buf, nBufSize);
}
